package com.baizhi.service.impl;

import com.baizhi.dao.ClazzDAO;
import com.baizhi.entity.Clazz;
import com.baizhi.service.ClazzService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class ClazzServiceImpl extends ServiceImpl<ClazzDAO, Clazz> implements ClazzService {

    @Autowired
    private ClazzDAO clazzDAO;

    @Override
    public List<Clazz> queryAll() {
        List<Clazz> clazzes = clazzDAO.selectList(null);
        return clazzes;
    }

    @Override
    public void delete(Long id) {
        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Clazz::getId, id);
        int delete = clazzDAO.delete(queryWrapper);
    }

    @Autowired
    HttpServletRequest request;

    @Override
    public Clazz add(MultipartFile logo, String name, Long tagId) {
        /**
         * 处理文件上传
         */
        String newLogoName = System.currentTimeMillis() + "_" + logo.getOriginalFilename();
        //根据相对路径，获取绝对路径
        String realPath = request.getSession().getServletContext().getRealPath("/logo");
        File file = new File(realPath, newLogoName);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
        }
        try {
            logo.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Clazz entity = new Clazz();
        entity.setName(name);
        entity.setPath(newLogoName);
        entity.setTagid(tagId);
        int insert = clazzDAO.insert(entity);
        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Clazz::getName, name);
        queryWrapper.eq(Clazz::getTagid, tagId);
        queryWrapper.eq(Clazz::getPath, newLogoName);
        Clazz clazz = clazzDAO.selectOne(queryWrapper);
        return clazz;
    }

    @Override
    public Clazz queryById(Long id) {
        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Clazz::getId, id);
        Clazz clazz = clazzDAO.selectOne(queryWrapper);
        return clazz;
    }
}
